import axios from "axios";
import config from "@/server/baseUrl"
import $store from "@/store/index"
import { Toast } from 'vant';
import router from '@/router' 

import { $loading, removeLoading } from "@/components/loading/js";
// 不需要错误提示的接口
const noErrorToast = ['task/test/get_temp_record'];
// 不展示loading的接口
const noLoading = [
    '/psychological/scheduling/get_message',
    '/main/index/get_token',
    '/psychological/scheduling/month_scheduling',
    '/psychological/scheduling/log_describe',
    'task/test/save_records'
];
const http = axios.create({
    baseURL: config.host,
    timeout: 600000,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
})


//请求拦截器
http.interceptors.request.use(config => {
    const token=sessionStorage.getItem('token')
    config.headers['token'] =token;
    if (!noLoading.includes(config.url)) {
        if (!document.getElementsByClassName('loading')[0]) {
            $loading({ visible: true });
        }
    }
    return config;
})


//相应拦截器
// ... existing code ...

// 相应拦截器
http.interceptors.response.use(response => {
    if (typeof response.data === 'string') {
        try {
            response.data = JSON.parse(response.data);
        } catch (error) {
            console.error('解析响应数据时出错:', error);
            if (!noLoading.includes(response.config.url)) removeLoading();
            return Promise.reject(error);
        }
    }
    if (response.data.code === 400) {
        router.push("/");
        if (!noLoading.includes(response.config.url)) removeLoading();
        // Toast.fail({ message: response.data.message })
    }
    // 错误消息提示
    if (response.data.code == 0) {
        if (!noErrorToast.includes(response.config.url)) Toast.fail({ message: response.data.message });
    }
    // 400为登录过期
    // else if(){}
    if (!noLoading.includes(response.config.url)) removeLoading();

    return response.data;
})


// ... existing code ...





export default http;


